package com.rf.richfitwheel.dyn.business.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.row.Row;
import com.rf.richfitwheel.admin.annotation.UserOperateLog;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageParameter;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.dyn.business.entity.BusinessCommonQueryParam;
import com.rf.richfitwheel.dyn.business.entity.BusinessDynamicParam;
import com.rf.richfitwheel.dyn.business.service.SysBusinessDynamicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/sysBusinessDynamic")
public class SysBusinessDynamicController {
    private static final Logger log = LoggerFactory.getLogger(SysBusinessDynamicController.class);
    @Resource
    private SysBusinessDynamicService sysBusinessDynamicService;

    /**
     * 分页查询通用业务数据表(业务的表单数据)。
     *
     * @param parameter 分页参数
     * @return 分页对象
     */
    @PostMapping("/page")
    public R page(@RequestBody PageParameter<BusinessCommonQueryParam> parameter) {
        Page<Row> page = sysBusinessDynamicService.queryByPage(parameter);
        return R.ok().put("page", page);
    }

    /**
     * 根据业务Id查询业务的表单数据
     *
     * @param parameter 参数
     * @return 数据
     */
    @PostMapping("/getInfoById")
    public R getInfoById(@RequestBody BusinessDynamicParam parameter) {
        BusinessDynamicParam busInfo = sysBusinessDynamicService.getDynBusinessInfoById(parameter);
        return R.ok().put("data", busInfo);
    }

    /**
     * 动态业务（表）数据保存或提交
     * @param businessDynamicParam 参数
     * @return 结果
     */
    @UserOperateLog(module = "通用动态业务数据", methods = "saveOrSubmitBusinessDynamic", description = "保存动态业务（表）数据")
    @PostMapping("/saveOrSubmitBusinessDynamic")
    public R saveOrSubmitBusinessDynamic(@RequestBody BusinessDynamicParam businessDynamicParam) {
        try{
            return R.ok().put("data", sysBusinessDynamicService.saveOrSubmitBusinessDynamic(businessDynamicParam));
        }catch(BusinessException be){
            log.error(be.getMessage(), be);
            return R.error(be.getMessage());
        }catch(JsonProcessingException be){
            log.error("解析表结构异常", be);
            return R.error("无法解析组件中预定义的表结构");
        }catch(Exception e){
            log.error("保存动态业务（表）数据失败", e);
            return R.error("保存动态业务（表）数据失败！");
        }
    }
}
